<template>
	<view :class="[
      'goods',
      { 'goods--square': shape === 'square' },
      { 'goods--rectangle': shape === 'rectangle' },
    ]" :style="[containStyle]">
		<!-- 商品图片 -->
		<view class="goods-images" :style="[imageStyle]">
			<u-image width="100%" height="100%" :src="image" mode="aspectFit" />
		</view>
		<!-- 商品信息 -->
		<view class="goods-content">
			<!-- 名称 -->
			<view class="goods-box goods-name line-2" v-if="titleShow" :style="{
          color: cardStyles.title_color,
        }">
				<slot name="name">{{ name }}</slot>
			</view>
			<view v-if="showHide.show_goods_tag && tag_desc != ''">
				<u-image width="80rpx" height="40rpx" :src="tag_desc" mode="scaleToFill" />
			</view>
			<!-- 编码 -->
			<view class="goods-box goods-code line-2" :style="{
          color: cardStyles.goods_code_color,
        }">
				<slot name="goods_code" v-if="showHide.show_goods_code">{{$zhTran('编码')}}：{{ goods_code }}</slot>
			</view>
			<!-- 型号 -->
			<view class="goods-box goods-model line-2" :style="{
          color: cardStyles.goods_model_color,
        }">
				<slot name="goods_model" v-if="showHide.show_goods_model">{{$zhTran('型号')}}：{{ goods_model }}</slot>
			</view>
			<!-- 库存 -->
			<view class="goods-box goods-stock line-2" :style="{
          color: cardStyles.goods_stock_color,
        }">
				<slot name="goods_stock" v-if="showHide.show_goods_stock">{{$zhTran('库存')}}：{{ goods_stock }}</slot>
			</view>

			<view class="goods-box goods-stock line-2" v-for="item,idx in field_list" :key="idx" :style="{
          color: item.title_color,
        }">
				<slot name="goods_stock">{{$zhTran(item.nickname)}}：{{ other_field_data[item.field_name]||'' }}</slot>
			</view>

			<view class="goods-gfa m-b-8" v-if="showHide.show_gfa_flag">
				<view class="gfa-tag">{{$zhTran('满赠')}}</view>
			</view>

			<!-- 扩展标签 -->
			<slot name="other-tag"></slot>
			<!-- 价格 -->
			<view class="goods-box goods-other" v-if="priceShow">
				<slot>
					<view class="flex">
						<text :style="{color:cardStyles.price_color}"
							v-if="showHide.show_price_text">{{$zhTran('销售价')}}:</text>
						<price :content="price" main-size="32rpx" minor-size="28rpx" :prefix="prefix"
							:color="cardStyles.price_color">
							<view slot="suffix">
								<price class="muted sm m-l-12" :line-through="true" :prefix="prefix"
									:color="cardStyles.scribing_price_color" :content="minPrice"
									v-show="Number(minPrice) && showHide.show_scribing_price" />
							</view>
						</price>
					</view>
				</slot>
			</view>
			<view class="goods-box goods-other" v-if="memberPriceShow">
				<slot>
					<view class="flex">
						<text :style="{color:cardStyles.member_price_color}"
							v-if="showHide.show_price_text">{{$zhTran('会员价')}}:</text>
						<price :content="member_price" main-size="32rpx" minor-size="28rpx" :prefix="prefix"
							:color="cardStyles.member_price_color">
						</price>
					</view>
				</slot>
			</view>

			<view v-if="Number(showHide.show_cart_icon)==1 && showHide.style <= 2">

				<view v-if="Number(showHide.show_cart_type)==0" class="cart-icon" @click.native.stop="addCart">
					<u-image width="100%" height="100%" :src="showHide.cart_icon_url" shape="circle"
						mode="scaleToFill" />
				</view>

				<view v-if="Number(showHide.show_cart_type)==1" class="m-t-10 flex row-right">
					<view class="flex row-center" v-if="spec_type == 2" @click.native.stop="addCart" :style="{
							borderRadius:'50rpx',
							padding:'10rpx 20rpx',
							backgroundColor:showHide.multi_specification_bg_color
						}">
						<text
							:style="{color:showHide.multi_specification_color}">{{showHide.multi_specification_desc}}</text>
					</view>
					<view v-else>
						<view class="flex row-right" v-if="cart_goods_ids.indexOf(Number(goods_id)) > -1">
							<u-number-box v-model="cartCount" :size="30" :icon-plus-color="showHide.cart_symbol_color"
								:long-press="false" :disabled-input="false" :cart_style="Number(showHide.cart_style)"
								:color="showHide.cart_number_color" :input-width="60" @click.native.stop=""
								:step="spec_value_list[0].step||1" :icon-minus-color="showHide.cart_symbol_color"
								:diy-plus-style="{
									 width:'50rpx',
									 bgColor:showHide.cart_btn_color+' !important',
									 borderRadius:'50rpx',
								 }" :diy-minus-style="{
									 width:'50rpx',
									 bgColor:showHide.cart_btn_color+' !important',
									 borderRadius:'50rpx',
								 }" />
						</view>
						<view class="flex row-center" v-else @click.native.stop="addCart" :style="{
							width:'50rpx',
							height:'50rpx',
							borderRadius:'50rpx',
							backgroundColor:showHide.cart_btn_color
						}">
							<u-icon name="plus" size="30" :color="showHide.cart_symbol_color"></u-icon>
						</view>
					</view>
				</view>
			</view>


		</view>
		<!-- 规格选择Popup -->
		<goods-spec v-model="showGoodsSpec" v-if="fromPage==''" :defaultInfo="{
			image: image,
			price: price,
			stock: goods_stock,
			show_goods_buycount:1,
			show_goods_price: 1,
			show_stock:showHide.show_goods_stock,
			aux_def_id:aux_def_id,
		}" :buttons="specButtonsList" :spec-list="spec_value" :spec-map="spec_value_list" @cart="handleCartAdd"
			:prefix="prefix" :understock_order_enabled="understock_order_enabled" />
	
		<!-- E 规格 -->
	</view>
</template>

<script>
	/**
	 * @description 商品卡片
	 * @property {String} shape 形状：square-正方形; rectangle-长方形 (默认: square)
	 * @property {String} image 商品图片
	 * @property {String} name 商品名称
	 * @property {String|Number} price 商品价格
	 * @property {String|Number|Boolean} minPrice 商品划线价格 (默认：false)
	 * @property {String} imageStyle 图片样式
	 * @property {String} containStyle 卡片样式
	 * @example <goods-card shape="rectangle" name="Muze" price="100" minPrice="120" />
	 */

	import {
		apiCartAdd,
		apiCartCountChange,
		apiCartDel, //商品删除
	} from "@/api/store";

	import {
		mapGetters,
		mapState
	} from "vuex";
	import {
		trottle,
	} from "@/utils/tools";
	import Cache from '@/utils/cache'

	export default {
		name: "GoodsCard",
		props: {
			// square -正方形 | rectangle -长方形
			fromPage: {
				type: String,
				default: "",
			},
			shape: {
				type: String,
				default: "square",
			},
			// 商品图片
			image: {
				type: String,
				default: "",
			},
			// 商品名称
			name: {
				type: String,
				default: "",
			},
			// 商品编码
			goods_code: {
				type: String,
				default: "",
			},
			// 商品型号
			goods_model: {
				type: String,
				default: "",
			},
			// 商品库存
			goods_stock: {
				type: [String, Number],
				default: 0,
			},
			// 价格
			price: {
				type: [String, Number],
				default: 0,
			},
			// 划线价
			minPrice: {
				type: [String, Number, Boolean],
				default: false,
			},
			// 会员价格
			member_price: {
				type: [String, Number, Boolean],
				default: false,
			},

			// 卡片样式
			containStyle: {
				type: Object,
				default: () => {},
			},

			// 图片样式
			imageStyle: {
				type: Object,
				default: () => {},
			},
			fieldShowHide: {
				type: Object,
				default: () => {},
			},
			fieldStyles: {
				type: [Object, Array],
			},

			// 前缀
			prefix: {
				type: String,
				default: "￥",
			},
			spec_type: {
				type: [String, Number],
				default: 1,
			},
			spec_id: {
				type: [String, Number],
				default: -1,
			},
			spec_value: {
				type: [Object, Array],
			},
			spec_value_list: {
				type: [Object, Array],
			},
			tag_desc: {
				type: String,
				default: "",
			},
			// 商品ID
			goods_id: {
				type: [String, Number],
				default: "",
			},
			cart_goods_ids: {
				type: Array,
				default: () => [],
			},
			cart_goods_arr: {
				type: Array,
				default: () => [],
			},
			aux_arr: {
				type: Array,
				default: [],
			},
			aux_def_id: {
				type: String,
				default: ''
			},
			other_field_data: {
				type: Array,
				default: [],
			},
			field_list: {
				type: Array,
				default: [],
			},
			// 负数出库
			understock_order_enabled: {
				type: [String, Number],
				default: 0,
			},
		},

		data() {
			return {
				// 页面状态
				goodsInfo: {}, // 商品信息
				showGoodsSpec: false, // 商品规格: 显示 | 隐藏
				goodsSpecOptions: {}, // 已选商品规格
				specButtonsList: [{
					event: "cart",
					text: this.$zhTran("加入购物车"),
				}, ], // 规格按钮
				showHide: {
					show_goods_tag: 0,
					show_goods_code: 0,
					show_goods_model: 0,
					show_goods_stock: 0,
					show_gfa_flag: 0,
					show_price_text: 1,
					show_scribing_price: 1,
					show_cart_icon: 0,
					cart_icon_url: ''
				},
				cardStyles: {
					title_color: this.themeColor,
					price_color: this.themeColor,
					member_price_color: this.themeColor,
					goods_code_color: this.themeColor,
					goods_model_color: this.themeColor,
					goods_stock_color: this.themeColor,
					scribing_price_color: this.themeColor,
				},
				cartCount: 0,
				cartIds: '',
			};
		},
		mounted() {
			// console.log('fieldShowHide', this.fieldShowHide)
			for (var idx in this.fieldShowHide) {
				this.showHide[idx] = !isNaN(Number(this.fieldShowHide[idx])) ? Number(this.fieldShowHide[idx]) : this
					.fieldShowHide[idx]
			}
			for (var idx in this.fieldStyles) {
				this.cardStyles[idx] = this.fieldStyles[idx]
			}

			var cart_arr = this.cart_goods_arr.filter(item => item.goods_id == this.goods_id)
			if (cart_arr.length > 0) {
				this.cartCount = cart_arr[0].num
				this.cartIds = cart_arr[0].cart_id
			}
		},
		computed: {
			...mapGetters(["isLogin"]),
			titleShow() {
				return this.fieldShowHide == undefined || this.fieldShowHide.show_title == undefined ?
					true :
					this.fieldShowHide.show_title;
			},
			priceShow() {
				return this.fieldShowHide == undefined || this.fieldShowHide.show_price == undefined ?
					true :
					this.fieldShowHide.show_price;
			},
			memberPriceShow() {
				return this.fieldShowHide == undefined || this.fieldShowHide.show_member_price == undefined || !Number(this
					.member_price) ? false : this.fieldShowHide.show_member_price;
			},
		},
		watch: {
			cart_goods_arr(data) {
				var cart_arr = data.filter(item => item.goods_id == this.goods_id)
				if (cart_arr.length > 0) {
					this.cartCount = cart_arr[0].num
					this.cartIds = cart_arr[0].cart_id
				}
			},
			cartCount(val) {
				var spec_info = this.spec_value_list.filter(item => item.id == this.spec_id)
				if (val < spec_info[0].min) val = 0
				if (val > 0) {
					this.changeCount(val)
				} else {
					if (this.cart_goods_ids.indexOf(this.goods_id) == -1) return

					apiCartDel({
							cart_id: this.cartIds,
						}).then((res) => {
							this.$store.dispatch("getCartNum");
						})
						.finally(() => {
							this.$emit('updateCartList', {});
						});
				}
			}
		},
		methods: {
			changeCount(val) {
				apiCartCountChange({
						cart_id: this.cartIds,
						goods_num: val,
					})
					.catch(() => {
						this.$emit('updateCartList', {});
					})
					.finally((res) => {
						this.$store.dispatch("getCartNum");
					})
			},
			addCart() {
				if (!this.isLogin) return this.$Router.push("/bundle2/pages/login/login");

				if (this.spec_type == 1 && this.aux_arr.length < 2) {
					// 处理 加入购物车
					var spec_info = this.spec_value_list.filter(item => item.id == this.spec_id)
					let aux_id = 0
					if (this.aux_arr.length == 1) aux_id = spec_info[0].aux_arr[0].id

					apiCartAdd({
							item_id: this.spec_id,
							goods_num: spec_info[0].min,
							clsp_id: Cache.get('clsp_id'),
							aux_id
						})
						.then(() => {
							this.$toast({
								title: this.$zhTran("已加入购物车"),
							});
							this.$store.dispatch("getCartNum");
							this.$emit('updateCartList', {});
						})
						.catch((err) => {
							throw new Error(err);
						});
				} else {
					this.showGoodsSpec = true;
				}
			},
			// 处理 加入购物车
			handleCartAdd({
				spec,
				number,
				aux_id
			}) {
				if (!this.isLogin) return this.$Router.push("/bundle2/pages/login/login");

				apiCartAdd({
						item_id: spec.id,
						goods_num: number,
						clsp_id: Cache.get('clsp_id'),
						aux_id
					})
					.then(() => {
						this.$toast({
							title: this.$zhTran("已加入购物车"),
						});
						this.$store.dispatch("getCartNum");
						this.$emit('updateCartList', {});
					})
					.catch((err) => {
						throw new Error(err);
					});
			},
		},
		onLoad() {
			this.changeCount = trottle(this.changeCount, 1000);
		},
	};
</script>

<style lang="scss" scoped>
	.goods {
		display: flex;
		border-radius: 7px;
		background-color: #ffffff;
		overflow: hidden;

		.cart-icon {
			position: absolute;
			right: 10rpx;
			bottom: 0;
			width: 50rpx;
			height: 50rpx;
		}

		&--square {
			flex-direction: column;
			width: 347rpx;
			min-height: 510rpx;

			.goods-images {
				width: 345rpx;
				height: 345rpx;
			}

			.goods-content {
				padding: 14rpx;
			}

			.cart-icon {
				right: 15rpx;
				bottom: 15rpx;
			}
		}

		&--rectangle {
			flex-direction: row;
			align-items: center;
			min-height: 320rpx;
			padding: 20rpx;

			.goods-images {
				box-sizing: border-box;
				width: calc(250rpx - 2 * 20rpx);
				height: calc(250rpx - 2 * 20rpx);
				border-radius: 7px;
				overflow: hidden;
			}

			.goods-content {
				margin-left: 20rpx;

				.goods-box {
					min-height: 40rpx;
				}
			}
		}

		&-content {
			box-sizing: border-box;
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			height: 100%;
			position: relative;

			.goods-other {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: flex-end;
			}
		}

		.gfa-tag {
			width: 80rpx;
			height: 40rpx;
			border: 1rpx solid red;
			border-radius: 6rpx;
			color: red;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.goods-name {
		font-size: $-font-size-nr;
		color: #333333;
		overflow: hidden;
	}
</style>